package com.turing.data.scripts.contract.filter

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.TypeReference
import com.turing.common.entity.TextVO
import com.turing.common.util.FileUtils
import com.turing.common.util.StringUtils
import com.turing.data.engine.utils.ScriptsUtils
import com.turing.data.vo.out.review.DependParamsVO
import com.turing.data.vo.out.review.TaskElementVO
import com.turing.data.engine.utils.RegexExtract

class OpenFrequency_30185_10_filter {

    static List<TaskElementVO.DrawResultVO> doConvert(DependParamsVO dependParams) {

        String REGEX = /.*开放期(:|：).*/

        def textPathMap = dependParams.textPathMap

        List<TaskElementVO.DrawResultVO> trueValueSet = new ArrayList<>()

        List<TaskElementVO.DrawResultVO > resultVOs = ScriptsUtils.tryInitResult(dependParams)
        if (resultVOs != null && resultVOs.size() > 0) {
            for (int i = 0; i < resultVOs.size(); i++) {
                if (StringUtils.isEmpty(resultVOs.get(i).childTaskSn)) {
//                    return  resultVOs
                    continue
                }
                def rawPath = textPathMap.get(resultVOs.get(i).childTaskSn)
                def rawText = FileUtils.loadJson(rawPath)
                def expandOffset = 0
                def start = resultVOs.get(i).start
                while( expandOffset < 10 && start > expandOffset ){
                    def expandString = rawText.substring(start-expandOffset,start)
                    if( expandString =~ REGEX  ){
                        trueValueSet.add(resultVOs.get(i))
                        return trueValueSet
                    }
                    expandOffset ++
                }
            }
        }

        dependParams.JSONTextMap.forEach(
                { childTaskSn, jsonText ->
                    TaskElementVO.DrawResultVO initDrawResultVO = new TaskElementVO.DrawResultVO()
                    initDrawResultVO.childTaskSn = childTaskSn
                    List<TextVO> textVOS = JSON.parseObject(jsonText, new TypeReference<ArrayList<TextVO>>() {})

                    def cleanText = "", start = 0, end = 0, page = -1
                    String REGEX1 = /(本计划自成立起，每运作|本计划自成立起，每个自然月|本计划每个自然季度|开放期：本集合计划成立之后)(.{1,150})(下一个工作日|开放期内可以办理参与、退出业务。|邮件告知为准|办理退出的情况除外）)/
                    String REGEX2 = /(本计划自成立起，每运作|本计划自成立起，每个自然月|本计划每个自然季度)(.{1,150})(邮件告知为准）。开放期内可以办理参与、退出业务。|邮件告知为准）。|起的5个工作日。|起的5个工作日，以此类推。|工作日。)/
                    String REGEX3 = /(?<=\(.{1,3}\)资产管理计划的封闭期和开放期.{1,40}开放期).{1,40}。/

                    RegexExtract.doRuleExtract(REGEX1,childTaskSn, dependParams, jsonText, trueValueSet)
                    println trueValueSet.toString()
                    if(trueValueSet.size()==0){
                        RegexExtract.doRuleExtract(REGEX2,childTaskSn, dependParams, jsonText, trueValueSet)
                    }
                    if(trueValueSet.size()==0){
                        RegexExtract.doRuleExtract(REGEX3,childTaskSn, dependParams, jsonText, trueValueSet)
                    }
                    if(trueValueSet.size()>0){
                        return
                    }

                    for (textVO in textVOS) {
                        def lines = textVO.paragraphs.get(0).lines
                        for (line in lines) {
                            cleanText = cleanText + line.objContent
                        }
                    }

                    def matchs = cleanText =~ REGEX1
                    def matchedGroupList = new ArrayList()
                    MatchedGroup matchedGroup
                    while (matchs.find()) {
                        matchedGroup = new MatchedGroup()
                        matchedGroup.sonOfStr = matchs.group()//子串内容
                        matchedGroup.indexStart = matchs.start()//子串在全文中的开始位置
                        matchedGroup.indexEnd = matchs.end()//子串在全文中的结束位置
                        matchedGroupList.add(matchedGroup)
                    }
                    if(matchedGroupList.isEmpty()){
                        matchs = cleanText =~ REGEX2
                        while (matchs.find()) {
                            matchedGroup = new MatchedGroup()
                            matchedGroup.sonOfStr = matchs.group()//子串内容
                            matchedGroup.indexStart = matchs.start()//子串在全文中的开始位置
                            matchedGroup.indexEnd = matchs.end()//子串在全文中的结束位置
                            matchedGroupList.add(matchedGroup)
                        }
                    }
                    matchedGroup = Collections.min(matchedGroupList)
                    initDrawResultVO.start = matchedGroup.indexStart
                    initDrawResultVO.end = matchedGroup.indexEnd
                    initDrawResultVO.text = matchedGroup.sonOfStr
                    initDrawResultVO.businessValue = matchedGroup.sonOfStr
                    initDrawResultVO.cus_sample_id = UUID.randomUUID()

                    def startflag = true
                    def endflag = true
                    def startLineId
                    def endLineId
                    for (textVO in textVOS) {
                        for (line in textVO.paragraphs.get(0).lines) {
                            if (start < initDrawResultVO.start) {
                                start = start + line.objContent.length()
                                startLineId = line.lineId
                            } else {
                                if (startflag) {
                                    initDrawResultVO.page = Integer.parseInt(line.lineId.split("_")[1])

                                    startflag = false
                                }

                            }
                            if (end < initDrawResultVO.end) {
                                end = end + line.objContent.length()
                                endLineId = line.lineId
                            } else {
                                if (endflag) {

                                    endflag = false
                                }
                            }
                            if ((!startflag) && (!endflag)) {
                                break
                            }

                        }
                        if ((!startflag) && (!endflag)) {
                            break
                        }

                    }
                    def startPage = startLineId.split("_")
                    def endPage = endLineId.split("_")
                    initDrawResultVO.startLineNo = Integer.valueOf(startPage[2])
                    initDrawResultVO.endLineNo = Integer.valueOf(endPage[2])
                    initDrawResultVO.pos_info = [
                            textVOS.get(Integer.valueOf(startPage[1])).paragraphs.get(0)
                                    .lines.get(Integer.valueOf(startPage[2])).objContent
                                    .indexOf(initDrawResultVO.text.substring(0, 2))
                            , textVOS.get(Integer.valueOf(endPage[1])).paragraphs.get(0)
                                    .lines.get(Integer.valueOf(endPage[2])).objContent
                                    .indexOf(initDrawResultVO.text.substring(initDrawResultVO.text.length() - 2))+2
                    ]
                    if (Integer.valueOf(startPage[1]) < Integer.valueOf(endPage[1])) {//不同页
                        for (int i = Integer.valueOf(startPage[1]); i <= Integer.valueOf(endPage[1]); i++) {
                            textVOS.get(i).paragraphs.get(0).lines.forEach({ line ->
                                def arr = line.lineId.split("_")
                                if (Integer.valueOf(arr[1]) == Integer.valueOf(startPage[1]) && Integer.valueOf(arr[2]) >= Integer.valueOf(startPage[2])) {
                                    if (initDrawResultVO.para_info == null) {
                                        def list = new ArrayList<>()
                                        list.add(line.lineId)
                                        initDrawResultVO.para_info = list
                                    } else if (!initDrawResultVO.para_info.contains(line.lineId)) {
                                        initDrawResultVO.para_info.add(line.lineId)
                                    }

                                } else if (Integer.valueOf(arr[1]) == Integer.valueOf(endPage[1]) && Integer.valueOf(arr[2]) <= Integer.valueOf(endPage[2])) {
                                    if (initDrawResultVO.para_info == null) {
                                        def list = new ArrayList<>()
                                        list.add(line.lineId)
                                        initDrawResultVO.para_info = list
                                    } else if (!initDrawResultVO.para_info.contains(line.lineId)) {
                                        initDrawResultVO.para_info.add(line.lineId)
                                    }
                                } else {
                                    if (initDrawResultVO.para_info == null) {
                                        def list = new ArrayList<>()
                                        list.add(line.lineId)
                                        initDrawResultVO.para_info = list
                                    } else if (!initDrawResultVO.para_info.contains(line.lineId)) {
                                        initDrawResultVO.para_info.add(line.lineId)
                                    }
                                }
                            })
                        }
                    } else {//在同一页
                        textVOS.get(Integer.valueOf(startPage[1])).paragraphs.get(0).lines.forEach({ line ->
                            if (line.lineNo >= Integer.valueOf(startPage[2]) && line.lineNo <= Integer.valueOf(endPage[2])) {
                                if (initDrawResultVO.para_info == null) {
                                    def list = new ArrayList<>()
                                    list.add(line.lineId)
                                    initDrawResultVO.para_info = list
                                } else if (!initDrawResultVO.para_info.contains(line.lineId)) {
                                    initDrawResultVO.para_info.add(line.lineId)
                                }
                            }
                        }
                        )
                    }

                    initDrawResultVO.type = 1
                    initDrawResultVO.global_pos = [start, end]
                    initDrawResultVO.degree = 0.0
                    initDrawResultVO.elem_truth
                    trueValueSet.add(initDrawResultVO)
                }
        )


        return trueValueSet
    }

    private static class MatchedGroup implements Comparable<MatchedGroup> {
        private long indexStart//子串在全文中的开始位置
        private long indexEnd //子串在全文中的结束位置
        private String sonOfStr//子串内容


        long getIndexStart() {
            return indexStart
        }

        void setIndexStart(long indexStart) {
            this.indexStart = indexStart
        }

        long getIndexEnd() {
            return indexEnd
        }

        void setIndexEnd(long indexEnd) {
            this.indexEnd = indexEnd
        }

        String getSonOfStr() {
            return sonOfStr
        }

        void setSonOfStr(String sonOfStr) {
            this.sonOfStr = sonOfStr
        }

        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder("{");
            sb.append("\"indexStart\":")
                    .append(indexStart);
            sb.append(",\"indexEnd\":")
                    .append(indexEnd);
            sb.append(",\"sonOfStr\":\"")
                    .append(sonOfStr).append('\"');
            sb.append('}');
            return sb.toString();
        }

        @Override
        int compareTo(MatchedGroup o) {
            return this.indexEnd - o.indexEnd
        }
    }

}
